﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Input.Touch;

namespace BandStandGuiro
{
    /// <summary>
    /// Implements IServiceProvider for the application. This type is exposed through the App.Services
    /// property and can be used for ContentManagers or other types that need access to an IServiceProvider.
    /// </summary>
    public class AppServiceProvider : IServiceProvider
    {
        // A map of service type to the services themselves
        private readonly Dictionary<Type, object> services = new Dictionary<Type, object>();

        /// <summary>
        /// Adds a new service to the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to add.</param>
        /// <param name="service">The service object itself.</param>
        public void AddService(Type serviceType, object service)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");
            if (service == null)
                throw new ArgumentNullException("service");
            if (!serviceType.IsAssignableFrom(service.GetType()))
                throw new ArgumentException("service does not match the specified serviceType");

            // Add the service to the dictionary
            services.Add(serviceType, service);
        }

        /// <summary>
        /// Gets a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to retrieve.</param>
        /// <returns>The service object registered for the specified type..</returns>
        public object GetService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Retrieve the service from the dictionary
            return services[serviceType];
        }

        /// <summary>
        /// Removes a service from the service provider.
        /// </summary>
        /// <param name="serviceType">The type of service to remove.</param>
        public void RemoveService(Type serviceType)
        {
            // Validate the input
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            // Remove the service from the dictionary
            services.Remove(serviceType);
        }
    }

    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        SoundEffect sound;
        Texture2D bg;

        List<SoundEffectInstance> instances;

        UIElementRenderer elementRenderer;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as BandStand.App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            sound = contentManager.Load<SoundEffect>("guiro");
            bg = contentManager.Load<Texture2D>("guirobg");

            instances = new List<SoundEffectInstance>();

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        Vector2 lastTouch;
        const int interval = 35;
        Rectangle guiro = new Rectangle(139, 169, 196, 469);
        const float pitchUp = 5;

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            foreach (TouchLocation t in TouchPanel.GetState())
            {
                if (t.State == TouchLocationState.Moved)
                {
                    //if (guiro.Contains(new Microsoft.Xna.Framework.Point((int)t.Position.X, (int)t.Position.Y)))
                    {
                        float delta = (float)Math.Abs(t.Position.Y - lastTouch.Y);
                        float intensity = Math.Min(1f, (delta / (float)interval) / pitchUp);
                        if (delta >= interval)
                        {
                            PlaySound(sound, intensity);
                        }
                        lastTouch = t.Position;
                    }
                }
            }

            //Remove done sounds
            for (int c = instances.Count - 1; c >= 0; c--)
            {
                if (instances[c].State == SoundState.Stopped)
                {
                    instances.RemoveAt(c);
                }
            }
        }

        private void PlaySound(SoundEffect sound, float intensity)
        {
            try
            {
                SoundEffectInstance inst = sound.CreateInstance();
                inst.Volume = intensity / 4 + 0.75f;
                inst.Pitch = intensity / 2;
                inst.Play();
                instances.Add(inst);
            }
            catch (InstancePlayLimitException e)
            {
                return;
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            spriteBatch.Draw(
                bg,
                Vector2.Zero,
                Color.White);

            elementRenderer.Render();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

            spriteBatch.End();
        }
    }
}